<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "./mixins/resize";
import { openDoorCount } from "@/api/home/statistics";

const animationDuration = 6000;

export default {
  name: "BarChart",
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart"
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "300px"
    }
  },
  data() {
    return {
      // chart: null
      yData: []
    };
  },
  created() {
    this.getData();
  },
  mounted() {
    this.$nextTick(() => {
      let that = this;
      setTimeout(function() {
        that.initChart();
      }, 100);
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },

  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, "macarons");

      Option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          top: 10,
          left: "2%",
          right: "2%",
          bottom: "3%",
          containLabel: true
        },
        legend: {
          data: ["时段通行人数统计"]
        },
        xAxis: [
          {
            type: "category",
            data: [
              "00:00-02:00",
              "02:00-04:00",
              "04:00-06:00",
              "06:00-08:00",
              "08:00-10:00",
              "10:00-12:00",
              "12:00-14:00",
              "14:00-16:00",
              "16:00-18:00",
              "18:00-20:00",
              "20:00-22:00",
              "22:00-24:00"
            ],
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: "value",
            axisTick: {
              show: false
            }
          }
        ],
        series: [
          {
            name: "时段通行人数统计",
            type: "bar",
            stack: "vistors",
            barWidth: "40%",
            data: this.yData,
            animationDuration
          }
        ]
      };

      this.chart.setOption(Option);
    },
    getData() {
      let that = this;
      openDoorCount().then(response => {
        let data = response.data;
        for (let i = 0; i < data.length; i++) {
          that.yData.push(data[i]);
        }
      });
    }
  }
};
</script>
